package org.rsbot.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.rsbot.bot.Bot;
import org.rsbot.script.Script;
import org.rsbot.script.internal.ScriptHandler;
import org.rsbot.script.internal.event.ScriptListener;
import org.rsbot.service.FileScriptSource;
import org.rsbot.service.ScriptBoxSource;
import org.rsbot.service.ScriptDefinition;
import org.rsbot.service.ScriptSource;
import org.rsbot.service.ServiceException;
import org.rsbot.util.GlobalConfiguration;
import org.rsbot.util.GlobalConfiguration.Paths;

public class ScriptSelector extends JDialog
  implements ScriptListener
{
  private static final long serialVersionUID = 5475451138208522511L;
  private static final String[] COLUMN_NAMES = { "", "Name", "Version", "Author", "Description" };

  private static final ScriptSource SRC_SOURCES = new FileScriptSource(new File(GlobalConfiguration.Paths.getScriptsSourcesDirectory()));
  private static final ScriptSource SRC_PRECOMPILED = new FileScriptSource(new File(GlobalConfiguration.Paths.getScriptsPrecompiledDirectory()));
  private static final ScriptSource SRC_BUNDLED;
  private static final ScriptSource SRC_DRM;
  private Bot bot;
  private JTable table;
  private JTextField search;
  private JComboBox accounts;
  private ScriptTableModel model;
  private List<ScriptDefinition> scripts;
  private JButton submit;

  public static void main(String[] paramArrayOfString)
  {
    new ScriptSelector(null, null).setVisible(true);
  }

  public ScriptSelector(Frame paramFrame, Bot paramBot)
  {
    super(paramFrame, "Script Selector");
    this.bot = paramBot;
    this.scripts = new ArrayList();
    this.model = new ScriptTableModel(this.scripts);
  }

  public void showGUI() {
    init();
    update();
    setVisible(true);
    load();
  }

  public void update() {
    boolean bool = this.bot.getScriptHandler().getRunningScripts().size() == 0;
    this.submit.setEnabled((bool) && (this.table.getSelectedRow() != -1));
    this.table.setEnabled(bool);
    this.search.setEnabled(bool);
    this.accounts.setEnabled(bool);
    this.table.clearSelection();
  }

  private void load() {
    this.scripts.clear();
    this.scripts.addAll(SRC_DRM.list());
    this.scripts.addAll(SRC_BUNDLED.list());
    this.scripts.addAll(SRC_PRECOMPILED.list());
    this.scripts.addAll(SRC_SOURCES.list());
    this.model.search(this.search.getText());
  }

  private void init() {
    setLayout(new BorderLayout());
    setDefaultCloseOperation(0);

    this.bot.getScriptHandler().addScriptListener(this);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent paramWindowEvent) {
        ScriptSelector.this.bot.getScriptHandler().removeScriptListener(ScriptSelector.this);
        ScriptSelector.this.dispose();
      }
    });
    this.table = new JTable(this.model) {
      public String getToolTipText(MouseEvent paramMouseEvent) {
        int i = rowAtPoint(paramMouseEvent.getPoint());
        ScriptDefinition localScriptDefinition = ScriptSelector.this.model.getDefinition(i);
        if (localScriptDefinition != null) {
          StringBuilder localStringBuilder = new StringBuilder();
          if (localScriptDefinition.authors.length > 1)
            localStringBuilder.append("Authors: ");
          else {
            localStringBuilder.append("Author: ");
          }
          int j = 0;
          for (String str : localScriptDefinition.authors) {
            if (j != 0)
              localStringBuilder.append(", ");
            else {
              j = 1;
            }
            localStringBuilder.append(str);
          }
          return localStringBuilder.toString();
        }
        return super.getToolTipText(paramMouseEvent);
      }
    };
    this.table.setRowHeight(20);
    this.table.setIntercellSpacing(new Dimension(1, 1));
    this.table.setSelectionMode(0);
    this.table.getSelectionModel().addListSelectionListener(new TableSelectionListener(null));
    setColumnWidths(this.table, new int[] { 30, 175, 50, 100 });

    JToolBar localJToolBar = new JToolBar();
    localJToolBar.setMargin(new Insets(1, 1, 1, 1));
    localJToolBar.setFloatable(false);

    this.search = new JTextField();
    this.search.addFocusListener(new FocusAdapter() {
      public void focusGained(FocusEvent paramFocusEvent) {
        ScriptSelector.this.table.clearSelection();
      }
    });
    this.search.addKeyListener(new KeyAdapter() {
      public void keyTyped(KeyEvent paramKeyEvent) {
        ScriptSelector.this.model.search(ScriptSelector.this.search.getText());
        ScriptSelector.this.table.revalidate();
      }
    });
    this.submit = new JButton("Start Script", new ImageIcon(GlobalConfiguration.getImage("/resources/images/control_play.png", GlobalConfiguration.Paths.ICON_START)));

    JButton localJButton = new JButton(new ImageIcon(GlobalConfiguration.getImage("/resources/images/disconnect.png", GlobalConfiguration.Paths.ICON_DISCONNECT)));

    this.submit.setEnabled(false);
    this.submit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent paramActionEvent) {
        ScriptDefinition localScriptDefinition = ScriptSelector.this.model.getDefinition(ScriptSelector.this.table.getSelectedRow());
        try {
          ScriptSelector.this.bot.setAccount((String)ScriptSelector.this.accounts.getSelectedItem());
          ScriptSelector.this.bot.getScriptHandler().runScript(localScriptDefinition.source.load(localScriptDefinition));
          ScriptSelector.this.bot.getScriptHandler().removeScriptListener(ScriptSelector.this);
          ScriptSelector.this.dispose();
        } catch (ServiceException localServiceException) {
          localServiceException.printStackTrace();
        }
      }
    });
    localJButton.setEnabled(false);
    localJButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent paramActionEvent)
      {
      }
    });
    this.accounts = new JComboBox(AccountManager.getAccountNames());
    this.accounts.setMinimumSize(new Dimension(200, 20));
    this.accounts.setPreferredSize(new Dimension(200, 20));

    localJToolBar.add(this.search);
    localJToolBar.add(Box.createHorizontalStrut(5));
    localJToolBar.add(this.accounts);
    localJToolBar.add(Box.createHorizontalStrut(5));
    localJToolBar.add(localJButton);
    localJToolBar.add(Box.createHorizontalStrut(5));
    localJToolBar.add(this.submit);

    JPanel localJPanel = new JPanel();
    localJPanel.setLayout(new BorderLayout());
    JScrollPane localJScrollPane = new JScrollPane(this.table, 20, 31);

    localJPanel.add(localJScrollPane, "Center");

    add(localJPanel, "Center");
    add(localJToolBar, "South");

    setSize(750, 400);
    setMinimumSize(getSize());
    setLocationRelativeTo(getParent());
    this.search.requestFocus();
  }

  private void setColumnWidths(JTable paramJTable, int[] paramArrayOfInt) {
    for (int i = 0; i < paramArrayOfInt.length; i++) {
      paramJTable.getColumnModel().getColumn(i).setPreferredWidth(paramArrayOfInt[i]);
      paramJTable.getColumnModel().getColumn(i).setMinWidth(paramArrayOfInt[i]);
      paramJTable.getColumnModel().getColumn(i).setMaxWidth(paramArrayOfInt[i]);
    }
  }

  public void scriptStarted(ScriptHandler paramScriptHandler, Script paramScript) {
    update();
  }

  public void scriptStopped(ScriptHandler paramScriptHandler, Script paramScript) {
    update();
  }

  public void scriptResumed(ScriptHandler paramScriptHandler, Script paramScript)
  {
  }

  public void scriptPaused(ScriptHandler paramScriptHandler, Script paramScript)
  {
  }

  public void inputChanged(Bot paramBot, int paramInt)
  {
  }

  static
  {
    if (GlobalConfiguration.RUNNING_FROM_JAR)
      SRC_BUNDLED = new FileScriptSource(new File(GlobalConfiguration.Paths.getScriptsExtractedCache()));
    else {
      SRC_BUNDLED = new FileScriptSource(new File("." + File.separator + "scripts"));
    }
    SRC_DRM = new ScriptBoxSource(LoginDialog.CREDENTIALS);
  }

  private static class ScriptTableModel extends AbstractTableModel
  {
    private static final long serialVersionUID = 1L;
    public static final ImageIcon ICON_SCRIPT_SRC = new ImageIcon(GlobalConfiguration.getImage("/resources/images/script_src.png", GlobalConfiguration.Paths.ICON_SCRIPT_SRC));

    public static final ImageIcon ICON_SCRIPT_PRE = new ImageIcon(GlobalConfiguration.getImage("/resources/images/script_pre.png", GlobalConfiguration.Paths.ICON_SCRIPT_PRE));

    public static final ImageIcon ICON_SCRIPT_DRM = new ImageIcon(GlobalConfiguration.getImage("/resources/images/script_drm.png", GlobalConfiguration.Paths.ICON_SCRIPT_DRM));

    public static final ImageIcon ICON_SCRIPT_BDL = new ImageIcon(GlobalConfiguration.getImage("/resources/images/script_bdl.png", GlobalConfiguration.Paths.ICON_SCRIPT_BDL));
    private List<ScriptDefinition> scripts;
    private List<ScriptDefinition> matches;

    public ScriptTableModel(List<ScriptDefinition> paramList)
    {
      this.scripts = paramList;
      this.matches = new ArrayList();
    }

    public void search(String paramString) {
      this.matches.clear();
      if (paramString.length() == 0) {
        this.matches.addAll(this.scripts);
      } else {
        paramString = paramString.toLowerCase();
        for (ScriptDefinition localScriptDefinition : this.scripts) {
          if (localScriptDefinition.name.toLowerCase().contains(paramString))
            this.matches.add(localScriptDefinition);
          else {
            for (String str : localScriptDefinition.keywords) {
              if (str.toLowerCase().contains(paramString)) {
                this.matches.add(localScriptDefinition);
                break;
              }
            }
          }
        }
      }
      fireTableDataChanged();
    }

    public ScriptDefinition getDefinition(int paramInt) {
      return (ScriptDefinition)this.matches.get(paramInt);
    }

    public int getRowCount() {
      return this.matches.size();
    }

    public int getColumnCount() {
      return ScriptSelector.COLUMN_NAMES.length;
    }

    public Object getValueAt(int paramInt1, int paramInt2) {
      if ((paramInt1 >= 0) && (paramInt1 < this.matches.size())) {
        ScriptDefinition localScriptDefinition = (ScriptDefinition)this.matches.get(paramInt1);
        if (paramInt2 == 0) {
          if (localScriptDefinition.source == ScriptSelector.SRC_SOURCES) {
            return ICON_SCRIPT_SRC;
          }
          if (localScriptDefinition.source == ScriptSelector.SRC_PRECOMPILED) {
            return ICON_SCRIPT_PRE;
          }
          if (localScriptDefinition.source == ScriptSelector.SRC_BUNDLED) {
            return ICON_SCRIPT_BDL;
          }
          return ICON_SCRIPT_DRM;
        }
        if (paramInt2 == 1) {
          return localScriptDefinition.name;
        }
        if (paramInt2 == 2) {
          return Double.valueOf(localScriptDefinition.version);
        }
        if (paramInt2 == 3) {
          StringBuilder localStringBuilder = new StringBuilder();
          for (String str : localScriptDefinition.authors) {
            localStringBuilder.append(str).append(", ");
          }
          return localStringBuilder.replace(localStringBuilder.length() - 2, localStringBuilder.length(), "");
        }
        if (paramInt2 == 4) {
          return localScriptDefinition.description;
        }
      }
      return null;
    }

    public Class<?> getColumnClass(int paramInt)
    {
      if (paramInt == 0) {
        return ImageIcon.class;
      }
      return String.class;
    }

    public String getColumnName(int paramInt)
    {
      return ScriptSelector.COLUMN_NAMES[paramInt];
    }
  }

  private class TableSelectionListener
    implements ListSelectionListener
  {
    private TableSelectionListener()
    {
    }

    public void valueChanged(ListSelectionEvent paramListSelectionEvent)
    {
      if (!paramListSelectionEvent.getValueIsAdjusting())
        ScriptSelector.this.submit.setEnabled(ScriptSelector.this.table.getSelectedRow() != -1);
    }
  }
}